#include "./handler_task.h"
#include "../utils/codec.h"
#include "../utils/proto.h"
#include "../driver/log_uart.h"
#include "../driver/motor.h"
#include "../driver/music_uart.h"
#include "../driver/display.h"

namespace task {

using namespace driver;
using namespace utils;

utils::Object<HandlerTask_t> handlerTask;

void HandlerTask_t::run() {
    
    ByteView_t bw;
    for (;;) {
        if (osOK != m_mq.poll(bw)) {
            continue;
        }
        uint16_t req = decode_uint16(bw.buf);
        logUart->printf("recv:%04x", req);
        switch (req) {
            case proto::MotorCtrl: on_motor_ctrl(bw); break;
            case proto::MusicVolumeCtrl: on_music_volume_ctrl(bw); break;
            case proto::MusicPlay: on_music_play(bw); break;
            case proto::Delivery: on_delivery(bw); break;
            case proto::Display: on_display(bw); break;
            case proto::PriceCtrl: on_set_price(bw); break;
        }
    }
}

void HandlerTask_t::on_motor_ctrl(const utils::ByteView_t &bw) {
    uint8_t sw = decode_uint8(bw.buf + 2);
    logUart->printf("sw:%d", sw);
    Error_t err;
    switch (sw) {
        case 0: motor->set_dir(Brake); break;
        case 1: motor->set_dir(CW); break;
        case 2: motor->set_dir(CCW); break;
        default: err = ec::Invalid; break;
    }
    logUart->write_uint8(proto::MotorCtrl, err.value());
}   

void HandlerTask_t::on_music_volume_ctrl(const utils::ByteView_t &bw) {
    uint8_t val = decode_uint8(bw.buf + 2);
    logUart->printf("volume:%d", val);
    musicUart->set_volume(val);
    logUart->write_uint8(proto::MusicVolumeCtrl, 0);
}

void HandlerTask_t::on_music_play(const utils::ByteView_t &bw) {
    uint8_t val = decode_uint8(bw.buf + 2);
    logUart->printf("play:%d", val);
    musicUart->play(val);
    logUart->write_uint8(proto::MusicPlay, 0);
}

void HandlerTask_t::on_delivery(const utils::ByteView_t &bw) {
    Error_t err = motor->run3();
    if (!err) {
        logUart->printf("出货成功");
    }
    logUart->write_uint8(proto::Delivery, err.value());
}

void HandlerTask_t::on_display(const utils::ByteView_t &bw) {
    uint8_t align = decode_uint8(bw.buf + 2);
    uint8_t val = decode_uint16(bw.buf + 3);
    logUart->printf("显示:%d %d", align, val);
    Align_t a = Right;
    if (align == 1) {
        a = Left;
    }
    display->show(a, val);
    logUart->write_uint8(proto::Display, 0);
}

void HandlerTask_t::on_set_price(const utils::ByteView_t &bw) {
    uint8_t price = decode_uint16(bw.buf + 2);
    display->set_price(price);
    logUart->write_uint8(proto::PriceCtrl, 0);
}

 
}
